package com.feiwo.nonego.rpc.loadbalancer.random;

import com.feiwo.nonego.rpc.loadbalancer.api.ServiceLoadBalancer;
import com.feiwo.nonego.rpc.spi.annotation.SPIClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 *
 *
 * @author feiwo 2025-08-12
 */
@SPIClass
public class RandomServiceLoadBalancer<T> implements ServiceLoadBalancer<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(RandomServiceLoadBalancer.class);

    @Override
    public T select(List<T> servers, int hashCode, String sourceIp) {
        LOGGER.info("基于随机算法的负载均衡策略");

        if (Objects.isNull(servers) || servers.isEmpty()) {
            return null;
        }

        final Random random = new Random();
        final int index = random.nextInt(servers.size());
        return servers.get(index);
    }
}
